<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    // 深拷贝---解决多层对象嵌套，当多层对象嵌套的时候，虽然首层对象拷贝是开辟了一个新的地址，但是在第一层之后就是只拷贝了地址，并没有开辟新的内存空间
    // 问题
    let obj = {
      name: "小灰",
      user: { name: "xiaohui" },
    };
    let XH = {
      name: obj.name,
      user: obj.user,
    };
    XH.user.name = "刘辉";
    console.log(JSON.stringify(XH, null, 2));
    console.log(JSON.stringify(obj, null, 2));

    // 解决方案--递归
    let data = {
      name: "小灰",
      user: { name: "xiaohui" },
    };
    function copy(object) {
      let res = {};
      for (const key in object) {
        res[key] =
          typeof object[key] === "object" ? copy(object[key]) : object[key];
      }
      return res;
    }
    let LH = copy(data);
    LH.user.name = "夏晓晓";
    console.log(JSON.stringify(LH, null, 2));
    console.log(JSON.stringify(data, null, 2));
  </script>
</html>
